import ProForm, {
    ModalForm,
    ProFormDigit,
    ProFormSelect,
    ProFormText,
    ProFormTextArea
} from '@ant-design/pro-form';
import React, { useEffect, useRef, useState } from 'react';
import { Input, message, Select } from 'antd';
import type { ModalProps } from 'antd';
import type {
    ProFormInstance,
} from '@ant-design/pro-form';
import styles from '../index.less';
import { useIntl } from 'umi';
import {
    getApiDataDictionaryCategorys as Categorys,
    postApiDataDictionary as Create,
    putApiDataDictionaryByKey as Update,
} from '@/services/furion-cms/dataDictionary';

const { Option } = Select;

interface DetailProps {
    modalVisible?: boolean;
    recored?: API.DataDictionaryDetailDto;
    onUpdate?: () => void;
    onVisibleChange: (visit: boolean) => void;
    modalProps?: Omit<ModalProps, 'visible'>;
}

const DetailViewer: React.FC<DetailProps> = (props) => {
    const { modalVisible, onUpdate, onVisibleChange, modalProps, recored } = props;
    /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
    const intl = useIntl();

    // 绑定一个 ProFormInstance 实例
    const formRef = useRef<ProFormInstance<API.DataDictionaryDetailDto>>();
    const [valueType, setValueType] = useState("value");
    const [categorys, setCategorys] = useState<API.DataDictionaryCategoryDto[]>();

    useEffect(() => {
        if (modalVisible) {
            (async () => {
                try {
                    const { data } = await Categorys();
                    setCategorys(data);
                } catch { }
            })();

            if (recored?.dataKey) {
                const dataValues = recored.dataValue?.split(',') ?? [];
                if (dataValues.length > 1) {
                    setValueType('values');
                    recored.dataValue = dataValues;
                }
                else setValueType('value');
            }
            else {
                setValueType('value');
            }
        }
    }, [modalVisible, recored]);

    const finishHandle = async (values: any) => {
        console.log('finishHandle', values);
        // 提交成功处理
        const successHandle = () => {
            // 清空数据
            message.success(intl.formatMessage({
                id: 'pages.dictionary.save.success',
                defaultMessage: '数据字典保存成功'
            }));
            onUpdate?.();
            return true;
        }

        if (recored?.dataKey) {
            return Update({ key: recored.dataKey }, values)
                .then(successHandle);
        }
        else {
            return Create(values)
                .then(successHandle);
        }
    };

    return (
        <ModalForm<API.DataDictionaryDetailDto>
            title={recored?.dataKey ? intl.formatMessage({
                id: 'pages.dictionary.detail.title.edit',
                defaultMessage: '编辑字典'
            }) : intl.formatMessage({
                id: 'pages.dictionary.detail.title.create',
                defaultMessage: '创建字典'
            })}
            modalProps={{
                destroyOnClose: true,
                width: 520,
                maskClosable: false,
                ...modalProps
            }}
            visible={modalVisible}
            initialValues={recored}
            onFinish={finishHandle}
            formRef={formRef}
            onVisibleChange={onVisibleChange}
        >
            <ProForm.Item label={intl.formatMessage({
                id: 'pages.dictionary.category-dataKey',
                defaultMessage: '类别/标识'
            })}
                tooltip={intl.formatMessage({
                    id: 'pages.dictionary.category-dataKey.tip',
                    defaultMessage: '唯一且不可更改,用于数据关联键'
                })} required>
                <Input.Group compact>
                    <ProFormSelect name="categoryId"
                        noStyle
                        placeholder={intl.formatMessage({
                            id: 'pages.dictionary.category-dataKey.placeholder_1',
                            defaultMessage: '请选择类别'
                        })}
                        fieldProps={{
                            className: styles.formInputGroupSelect,
                            options: categorys?.map(m => ({ label: m.name!, value: m.id! }))
                        }}
                        rules={[
                            {
                                required: true,
                                message: intl.formatMessage({
                                    id: 'pages.dictionary.category-dataKey.required_1',
                                    defaultMessage: '请选择数据类别'
                                })
                            }
                        ]}
                    />
                    <ProFormText
                        name="dataKey"
                        noStyle
                        placeholder={intl.formatMessage({
                            id: 'pages.dictionary.category-dataKey.placeholder_2',
                            defaultMessage: '请输入字典标识名'
                        })}
                        fieldProps={{
                            className: styles.formInputGroupValue
                        }}
                        rules={[
                            {
                                required: true,
                                message: intl.formatMessage({
                                    id: 'pages.dictionary.category-dataKey.required_2',
                                    defaultMessage: '请输入字典标识名'
                                })
                            },
                            {
                                pattern: /^[0-9a-zA-Z_]{4,50}$/,
                                message: intl.formatMessage({
                                    id: 'pages.dictionary.category-dataKey.pattern',
                                    defaultMessage: '标识名只能是字母、数字或是字母数字混合组成且长度为4~50'
                                })
                            }
                        ]}
                    />
                </Input.Group>
            </ProForm.Item>
            <ProForm.Item label={intl.formatMessage({
                id: 'pages.dictionary.dataValue',
                defaultMessage: '数据值'
            })}
                tooltip={intl.formatMessage({
                    id: 'pages.dictionary.dataValue.tip',
                    defaultMessage: '标识对应的数据值或数据列表'
                })} required>
                <Input.Group compact>
                    <Select value={valueType} className={styles.formInputGroupSelect} onChange={setValueType}>
                        <Option value="value">{intl.formatMessage({
                            id: 'pages.dictionary.dataValue.type.single',
                            defaultMessage: '单一值'
                        })}</Option>
                        <Option value="values">{intl.formatMessage({
                            id: 'pages.dictionary.dataValue.type.list',
                            defaultMessage: '数据列表'
                        })}</Option>
                    </Select>
                    {valueType === "value" ? <ProFormText
                        name="dataValue"
                        noStyle
                        fieldProps={{
                            className: styles.formInputGroupValue
                        }}
                        rules={[
                            {
                                required: true,
                                message: intl.formatMessage({
                                    id: 'pages.dictionary.dataValue.required',
                                    defaultMessage: '请输入字典标识的数据值'
                                })
                            }
                        ]}
                    /> : <ProFormSelect name="dataValue"
                        noStyle
                        fieldProps={{
                            className: styles.formInputGroupValue,
                            mode: 'tags',
                        }}
                        rules={[
                            {
                                required: true,
                                message: intl.formatMessage({
                                    id: 'pages.dictionary.dataValue.required',
                                    defaultMessage: '请输入字典标识的数据值'
                                })
                            }
                        ]}
                        transform={(value: any, field: string, object: API.LoginParams) => {
                            if (Array.isArray(value)) {
                                object[field] = value.join(',');
                            }
                            return object;
                        }}
                    />}

                </Input.Group>
            </ProForm.Item>
            <ProFormDigit name="sortNumber"
                label={intl.formatMessage({
                    id: 'pages.dictionary.sortNumber',
                    defaultMessage: '排序号'
                })} />
            <ProFormTextArea
                name="description"
                label={intl.formatMessage({
                    id: 'pages.dictionary.description',
                    defaultMessage: '名称或描述'
                })}
            />
        </ModalForm>
    )
}

export default DetailViewer;